/**
 * @description:
 * @file: permission.ts
 * @author: Evan
 * @date: 2025.04.09 11:30:02
 * @week: 周三
 * @version: V
 * */

import NProgress from 'nprogress'
import router from './router'

import { useAuthStore, useAppStore, useUserStore } from './stores'
import type { RouteItem } from './router/type'
import i18n from './locales'
const { t } = i18n.global

// 路由拦截器
router.beforeEach(async (to, _from, next) => {
  // 开始加载进度条
  NProgress.start()

  // 设置页面标题
  const dom: Document = document
  const title = to.meta.title as string
  const mult = to.meta.mult as string
  const appStore = useAppStore()
  if (appStore.i18n && mult) {
    dom.title = mult ? t(`route.${mult}`).toUpperCase() : title || 'loading...'
  } else {
    dom.title = title || '后台管理'
  }

  const userStore = useUserStore()
  // 判断用户是否登录
  const token = userStore.token
  const loginPath = '/login'
  if (token) {
    if (to.path == loginPath) {
      // 已登录直接重定向到首页
      next({ path: `/` })
    } else {
      // 判断权限
      const hasPowers = userStore.powers && userStore.powers.length > 0

      if (hasPowers) {
        next()
      } else {
        try {
          // 获取权限
          const permissions = await userStore.getUserInfo()

          const authStore = useAuthStore()
          // 获取可访问路由
          const accessRoutes = await authStore.generateRoutes(permissions)

          // 动态添加路由
          accessRoutes.forEach((route: RouteItem) => {
            const hasRoute = router.hasRoute(route.name as string)
            if (!hasRoute) {
              router.addRoute(route)
            }
          })

          next({ ...to, replace: true })
        } catch (error) {
          console.log('路由守卫：', error)
          // await userStore.resetToken()
          // next(`${loginPath}?redirect=${to.path}`)
        }
      }
    }
  } else {
    if (to.path == loginPath) {
      next()
    } else {
      // 跳转登录页面
      next(`${loginPath}?redirect=${to.path}`)
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
